package cn.qu.dockman.mgr.service.impl;

import cn.qu.dockman.mgr.entity.Container;
import cn.qu.dockman.mgr.example.ContainerExample;
import cn.qu.dockman.mgr.mapper.ContainerMapper;
import cn.qu.dockman.mgr.service.ContainerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by zh on 17/3/17.
 */
@Service
public class ContainerServiceImpl implements ContainerService {
    @Autowired
    private ContainerMapper containerMapper;

    @Override
    public Container findContainer(int hostId, int imageId, String containerId) {
        List<Container> containerList = containerMapper.selectByExample(new ContainerExample() {{
            createCriteria().andHostIdEqualTo(hostId)
                    .andImageIdEqualTo(imageId)
                    .andContainerIdEqualTo(containerId);
        }});
        if (containerList == null || containerList.isEmpty()) {
            return null;
        } else {
            return containerList.get(0);
        }
    }

    @Override
    public void saveOrUpdate(Container container) {
        if (container.getId() == null) {
            containerMapper.insert(container);
        } else {
            containerMapper.updateByPrimaryKey(container);
        }
    }

    @Override
    public List<Container> findByHostId(int hostId) {
        return containerMapper.selectByExample(new ContainerExample() {{
            createCriteria().andHostIdEqualTo(hostId);
        }});
    }

    @Override
    public void delete(Container container) {
        containerMapper.deleteByPrimaryKey(container.getId());
    }
}
